/**
 * 路由汇总
 */
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');

module.exports = function(pool) {
  // 诊断相关路由
  const diagnosisRoutes = require('./diagnosis')(pool);
  router.use('/diagnosis', diagnosisRoutes);
  
  // 健康检查端点
  router.get('/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date() });
  });
  
  // 提供查看最新日志的API
  router.get('/logs/latest', (req, res) => {
    try {
      const logDir = path.join(__dirname, '../logs');
      
      // 确保日志目录存在
      if (!fs.existsSync(logDir)) {
        return res.status(404).json({
          success: false,
          message: '日志目录不存在'
        });
      }
      
      // 获取所有日志文件
      const logFiles = fs.readdirSync(logDir)
        .filter(file => file.endsWith('.log'))
        .sort()
        .reverse();
      
      if (logFiles.length === 0) {
        return res.status(404).json({
          success: false,
          message: '没有找到日志文件'
        });
      }
      
      // 读取最新的日志文件
      const latestLog = fs.readFileSync(path.join(logDir, logFiles[0]), 'utf8');
      
      // 返回日志内容
      res.json({
        success: true,
        filename: logFiles[0],
        content: latestLog
      });
    } catch (err) {
      res.status(500).json({
        success: false,
        message: '获取日志失败',
        error: err.message
      });
    }
  });

  // 注册用户认证路由
  const authRoutes = require('./auth')(pool);
  router.use('/auth', authRoutes);

  return router;
};
